import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/utils/kudo_helper.dart';
import '../../utils/kudo_colors.dart';
import '../../utils/image_resource_helper.dart';
import '../../state/chat/kite_chat_controller.dart';
import '../../state/chat/kite_chat_session_entity.dart';
import '../../state/chat/kite_chat_message_entity.dart';
import '../../state/person/persona_session_controller.dart';
import '../../widget/report_dialog.dart';
import '../../router/app_navigation_manager.dart';

class KitePrivateChatScreen extends StatefulWidget {
  final KiteChatSessionEntity sessionData;

  const KitePrivateChatScreen({super.key, required this.sessionData});

  @override
  State<KitePrivateChatScreen> createState() => _KitePrivateChatScreenState();
}

class _KitePrivateChatScreenState extends State<KitePrivateChatScreen>
    with TickerProviderStateMixin {
  final TextEditingController _inputController = TextEditingController();
  final ScrollController _messagesScrollController = ScrollController();
  late AnimationController _fadeAnimationController;
  late Animation<double> _fadeAnimation;
  bool _hasInitialized = false;

  @override
  void initState() {
    super.initState();
    _setupAnimations();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _performInitialization();
  }

  void _setupAnimations() {
    _fadeAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeAnimationController, curve: Curves.easeIn),
    );
  }

  void _performInitialization() {
    if (!_hasInitialized) {
      _hasInitialized = true;

      Future.microtask(() {
        KiteChatController.globalInstance.selectChatSession(
          widget.sessionData.uniqueIdentifier,
        );

        _fadeAnimationController.forward();

        WidgetsBinding.instance.addPostFrameCallback((_) {
          _scrollToLatestMessage();
        });
      });
    }
  }

  void _scrollToLatestMessage() {
    if (_messagesScrollController.hasClients) {
      _messagesScrollController.animateTo(
        _messagesScrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 250),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  void dispose() {
    _inputController.dispose();
    _messagesScrollController.dispose();
    _fadeAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/chat_background.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          child: FadeTransition(
            opacity: _fadeAnimation,
            child: Column(
              children: [
                _constructHeaderSection(),
                _constructMessagesSection(),
                _constructInputSection(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _constructHeaderSection() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return const SizedBox.shrink();

    final otherUserId = widget.sessionData.getOtherParticipantId(
      currentUser.uniqueIdentifier,
    );
    final otherUser = PersonaSessionController.quickGetUserById(otherUserId);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => GoRouter.of(context).pop(),
            child: Icon(
              Icons.arrow_back_ios_new,
              size: 18.sp,
              color: KudoColors.black,
            ),
          ),

          SizedBox(width: 10.w),

          Container(
            decoration: BoxDecoration(shape: BoxShape.circle),
            child: ImageResourceHelper.buildCircularAvatar(
              imagePath: otherUser?.avatarResourceUrl ?? '',
              radius: 25.r,
            ),
          ),

          SizedBox(width: 15.w),

          Text(
            otherUser?.displayAlias ?? 'Unknown',
            style: GoogleFonts.lato(
              fontSize: 18.sp,
              fontWeight: FontWeight.w700,
              color: KudoColors.black,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),

          const Spacer(),

          GestureDetector(
            onTap: () => _startVideoCall(),
            child: Container(
              padding: EdgeInsets.all(8.w),
              child: Icon(Icons.videocam, size: 26.sp, color: KudoColors.green),
            ),
          ),

          SizedBox(width: 10.w),

          GestureDetector(
            onTap: _displayReportDialog,
            child: Container(
              padding: EdgeInsets.all(8.w),
              child: SvgPicture.asset(
                'assets/svg/report.svg',
                width: 26.w,
                height: 26.h,
                colorFilter: ColorFilter.mode(
                  KudoColors.black,
                  BlendMode.srcIn,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _constructMessagesSection() {
    return Expanded(
      child: Container(
        decoration: BoxDecoration(
          color: KudoColors.chatBackground,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(28.r),
            topRight: Radius.circular(28.r),
          ),
        ),
        child:
            KiteChatController.globalInstance.currentSessionMessagesState
                    .reactiveValue(context)
                    .isEmpty
                ? _constructEmptyMessagesView()
                : _constructMessagesListView(),
      ),
    );
  }

  Widget _constructEmptyMessagesView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(
              color: KudoColors.green.withValues(alpha: 0.1),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.chat_outlined,
              size: 50.sp,
              color: KudoColors.green,
            ),
          ),
          SizedBox(height: 20.h),
          Text(
            'Start your conversation!',
            style: GoogleFonts.lato(
              fontSize: 17.sp,
              color: KudoColors.black.withValues(alpha: 0.7),
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _constructMessagesListView() {
    final messages = KiteChatController
        .globalInstance
        .currentSessionMessagesState
        .reactiveValue(context);

    return ListView.separated(
      controller: _messagesScrollController,
      padding: EdgeInsets.all(20.w),
      itemCount: messages.length,
      separatorBuilder: (context, index) => SizedBox(height: 15.h),
      itemBuilder: (context, index) {
        return _constructMessageBubble(messages[index]);
      },
    );
  }

  Widget _constructMessageBubble(KiteChatMessageEntity message) {
    if (message.messageType == ChatMessageType.missedCall) {
      return _constructMissedCallMessage(message);
    }

    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    final isMyMessage =
        currentUser?.uniqueIdentifier == message.senderPersonaId;
    final sender = PersonaSessionController.quickGetUserById(
      message.senderPersonaId,
    );

    return Align(
      alignment: isMyMessage ? Alignment.centerRight : Alignment.centerLeft,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMyMessage) ...[
            Container(
              margin: EdgeInsets.only(right: 10.w),
              child: ImageResourceHelper.buildCircularAvatar(
                imagePath: sender?.avatarResourceUrl ?? '',
                radius: 20.r,
              ),
            ),
          ],

          Flexible(
            child: Column(
              crossAxisAlignment:
                  isMyMessage
                      ? CrossAxisAlignment.end
                      : CrossAxisAlignment.start,
              children: [
                Container(
                  constraints: BoxConstraints(maxWidth: 250.w),
                  padding: EdgeInsets.symmetric(
                    horizontal: 18.w,
                    vertical: 14.h,
                  ),
                  decoration: BoxDecoration(
                    color: isMyMessage ? KudoColors.yellow : KudoColors.green,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(isMyMessage ? 18.r : 5.r),
                      topRight: Radius.circular(isMyMessage ? 5.r : 18.r),
                      bottomLeft: Radius.circular(18.r),
                      bottomRight: Radius.circular(18.r),
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withValues(alpha: 0.08),
                        offset: const Offset(0, 3),
                        blurRadius: 6,
                      ),
                    ],
                  ),
                  child: Text(
                    message.messageTextContent,
                    style: GoogleFonts.lato(
                      fontSize: 15.sp,
                      color: isMyMessage ? Colors.black : Colors.white,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ).configWidget(borderRadius: 18.r),
              ],
            ),
          ),

          if (isMyMessage) ...[
            Container(
              margin: EdgeInsets.only(left: 10.w),
              child: ImageResourceHelper.buildCircularAvatar(
                imagePath: currentUser?.avatarResourceUrl ?? '',
                radius: 20.r,
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建输入区域
  Widget _constructInputSection() {
    return Container(
      decoration: BoxDecoration(color: Colors.transparent),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        child: Row(
          children: [
            // 输入框容器
            Expanded(
              child: Container(
                height: 52.h,
                decoration: BoxDecoration(
                  color: KudoColors.yellow,
                  borderRadius: BorderRadius.circular(26.r),
                ),
                child: Row(
                  children: [
                    // 文本输入框
                    Expanded(
                      child: TextField(
                        controller: _inputController,
                        style: GoogleFonts.lato(
                          fontSize: 15.sp,
                          color: KudoColors.black,
                          fontWeight: FontWeight.w400,
                        ),
                        decoration: InputDecoration(
                          hintText: 'Start Telling Your Story',
                          hintStyle: GoogleFonts.lato(
                            fontSize: 15.sp,
                            color: KudoColors.black.withValues(alpha: 0.4),
                            fontWeight: FontWeight.w400,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 20.w,
                          ),
                        ),
                        maxLines: 1,
                        textInputAction: TextInputAction.send,
                        onSubmitted: (_) => _handleMessageSend(),
                      ),
                    ),

                    SizedBox(width: 8.w),

                    GestureDetector(
                      onTap: _startVideoCall,
                      child: Container(
                        width: 38.w,
                        height: 38.h,
                        decoration: BoxDecoration(
                          color: KudoColors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                          child: SvgPicture.asset(
                            'assets/svg/video.svg',
                            width: 20.w,
                            height: 20.h,
                            colorFilter: ColorFilter.mode(
                              KudoColors.yellow,
                              BlendMode.srcIn,
                            ),
                          ),
                        ),
                      ),
                    ),

                    SizedBox(width: 8.w),

                    GestureDetector(
                      onTap: _handleMessageSend,
                      child: Container(
                        width: 38.w,
                        height: 38.h,
                        margin: EdgeInsets.only(right: 7.w),
                        decoration: BoxDecoration(
                          color: KudoColors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                          child: SvgPicture.asset(
                            'assets/svg/send.svg',
                            width: 20.w,
                            height: 20.h,
                            colorFilter: ColorFilter.mode(
                              KudoColors.yellow,
                              BlendMode.srcIn,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ).configWidget(borderRadius: 26.r),
            ),
          ],
        ),
      ),
    );
  }

  void _handleMessageSend() {
    final messageText = _inputController.text.trim();
    if (messageText.isEmpty) return;

    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return;

    final otherUserId = widget.sessionData.getOtherParticipantId(
      currentUser.uniqueIdentifier,
    );

    final success = KiteChatController.globalInstance.sendTextMessage(
      targetUserId: otherUserId,
      messageContent: messageText,
    );

    if (success) {
      _inputController.clear();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToLatestMessage();
      });
    }
  }

  void _startVideoCall() {
    AppNavigationManager.navigateToKiteVideoCall(context, widget.sessionData);
  }

  void _displayReportDialog() {
    ReportDialog.show(
      context: context,
      title: 'Report Private Chat',
      onReport: (reportType) {
        _handleReportSubmission();
      },
    );
  }

  void _handleReportSubmission() {
    KudoToast.showSuccessToast(context, 'Report submitted successfully');

    KiteChatController.globalInstance.deleteChatSession(
      widget.sessionData.uniqueIdentifier,
    );

    Future.delayed(const Duration(seconds: 1), () {
      if (mounted) {
        GoRouter.of(context).pop();
      }
    });
  }

  Widget _constructMissedCallMessage(KiteChatMessageEntity message) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return const SizedBox.shrink();

    String callerId;
    if (message.senderPersonaId == 'system') {
      callerId = widget.sessionData.getOtherParticipantId(
        currentUser.uniqueIdentifier,
      );
    } else {
      callerId = message.senderPersonaId;
    }

    final caller = PersonaSessionController.quickGetUserById(callerId);
    final isMyCall = callerId == currentUser.uniqueIdentifier;

    return Align(
      alignment: isMyCall ? Alignment.centerRight : Alignment.centerLeft,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMyCall) ...[
            Container(
              margin: EdgeInsets.only(right: 10.w),
              child: ImageResourceHelper.buildCircularAvatar(
                imagePath: caller?.avatarResourceUrl ?? '',
                radius: 20.r,
              ),
            ),
          ],

          Flexible(
            child: Container(
              constraints: BoxConstraints(maxWidth: 250.w),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(isMyCall ? 18.r : 5.r),
                  topRight: Radius.circular(isMyCall ? 5.r : 18.r),
                  bottomLeft: Radius.circular(18.r),
                  bottomRight: Radius.circular(18.r),
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black,
                    offset: const Offset(0, 4),
                    blurRadius: 0,
                  ),
                ],
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SvgPicture.asset(
                    'assets/svg/no_answer.svg',
                    width: 26.w,
                    height: 26.h,
                    colorFilter: ColorFilter.mode(
                      KudoColors.black,
                      BlendMode.srcIn,
                    ),
                  ),

                  SizedBox(width: 10.w),

                  Flexible(
                    child: Text(
                      "The Other Party Did Not Answer",
                      style: GoogleFonts.lato(
                        fontSize: 13.sp,
                        color: KudoColors.black.withValues(alpha: 0.8),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          if (isMyCall) ...[
            Container(
              margin: EdgeInsets.only(left: 10.w),
              child: ImageResourceHelper.buildCircularAvatar(
                imagePath: currentUser.avatarResourceUrl,
                radius: 20.r,
              ),
            ),
          ],
        ],
      ),
    );
  }
}
